﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using STF.OrangeDog.Model;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using STF.OrangeDog.IRepository;

namespace STF.OrangeDog.Repository
{
    public class BaseDal<T>:IBaseDal<T> where T:BaseModel,new()
    {
        private ADbContext _db;
        public BaseDal(ADbContext db) 
        {
          _db = db;
        }
        public async Task<int> AddModelAsync(T model)
        {
            _db.Entry(model).State = EntityState.Added;
            return await _db.SaveChangesAsync();
        }

        public async Task<int> EditModelAsync(T model)
        {
            _db.Entry(model).State = EntityState.Modified;
            return await _db.SaveChangesAsync();
        }

        public async Task<IEnumerable<T>> GetAllAsync()
        {
            return await _db.Set<T>().OrderByDescending(t => t.UpdateTime).ToListAsync();
        }

        public async Task<IEnumerable<T>> GetDataByChooseAsync(Expression<Func<T, bool>> whereLambda)
        {
            return await _db.Set<T>().Where(whereLambda).OrderByDescending(t => t.UpdateTime).ToListAsync();
        }

        public async Task<T> GetDataByIdAsync(int id)
        {
            return await _db.Set<T>().FindAsync(id);
        }

        public async Task<int> RemoveModelAsync(T model)
        {
            _db.Entry(model).State = EntityState.Deleted;
            return await _db.SaveChangesAsync();
        }

    }
}
